import { createRouter, createWebHistory } from "vue-router";
import { isLoggedIn } from "../utils/auth";
import HomeView from "../views/HomeView.vue";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("../views/LoginView.vue"),
      meta: { requiresAuth: false },
    },
    {
      path: "/register",
      name: "register",
      component: () => import("../views/RegisterView.vue"),
      meta: { requiresAuth: false },
    },
    {
      path: "/",
      name: "home",
      component: HomeView,
      meta: { requiresAuth: true },
    },
    {
      path: "/material",
      name: "material",
      component: () => import("../views/MaterialListView.vue"),
      meta: { requiresAuth: true },
    },
    {
      path: "/copywriting",
      name: "copywriting",
      component: () => import("../views/CopywritingView.vue"),
      meta: { requiresAuth: true },
    },
    {
      path: "/expand",
      name: "expand",
      component: () => import("../views/ImageExpandView.vue"),
      meta: { requiresAuth: true },
    },
    {
      path: "/export",
      name: "export",
      component: () => import("../views/ExportView.vue"),
      meta: { requiresAuth: true },
    },
    {
      path: "/history",
      name: "history",
      component: () => import("../views/HistoryView.vue"),
      meta: { requiresAuth: true },
    },
    {
      path: "/favorite",
      name: "favorite",
      component: () => import("../views/FavoriteView.vue"),
      meta: { requiresAuth: true },
    },
  ],
});

// 路由守卫
router.beforeEach((to, from, next) => {
  // 检查路由是否需要认证
  if (to.meta.requiresAuth === false) {
    // 登录页面，直接通过
    next();
    return;
  }

  // 检查登录状态
  if (!isLoggedIn()) {
    // 未登录或已过期，跳转到登录页
    console.log("用户未登录或登录已过期，跳转到登录页");
    next("/login");
    return;
  }

  // 已登录，允许访问
  next();
});

export default router;
